layui.use(["layer", "echarts"], function () {
  // 2020-03-25 HF sessionStorage中取出数据
  var token = sessionStorage.getItem("newtoken");
  //  给曲线具体位置名称 xx/xx/xx/某某折线图
  var SaveCurveName = JSON.parse(sessionStorage.getItem("SaveCurveName"));
  //  接口上传需要的数据
  var HcurveName = sessionStorage.getItem("SaveName");

  var $ = layui.jquery,
    echarts = layui.echarts;
  $("#Myloading2").remove();
  /*************曲线图初始化*******************/
  var beginTime1 = $("#beginTime").val();
  var endTime1 = $("#endTime").val();

  if (beginTime1 == "" && endTime1 == "") {
    function add0(m) {
      return m < 10 ? "0" + m : m;
    } //避免少0
    // 当前时间
    var time = new Date();
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    var s2 =
      year +
      "-" +
      add0(month) +
      "-" +
      add0(date) +
      " " +
      add0(hours) +
      ":" +
      add0(minutes) +
      ":" +
      add0(seconds);
    // var s2 = setInterval(function(){
    //     return 2
    // })
    // console.log(s2);
    var s1 =
      year +
      "-" +
      add0(month) +
      "-" +
      add0(date) +
      " " +
      add0(0) +
      ":" +
      add0(0) +
      ":" +
      add0(0);
    $("#beginTime").val(s1);
    $("#endTime").val(s2);

    // 实时更新当前时间
    var cltime = setInterval(function () {
      let nowtime = new Date();
      var s1 = GMTToStr(nowtime);
      $("#endTime").val(s1);
    }, 1000);

    // 初始化为当前一天的时间
    beginTime1 = s1;
    endTime1 = s2;
    $.ajax({
      url:
        "/oms-web/curves-authority-points?token=" +
        token +
        "&beginTime=" +
        beginTime1 +
        "&endTime=" +
        endTime1,
      dataType: "json",
      type: "POST",
      data: HcurveName,
      contentType: "application/json",
      success: function (data) {
        if (data.code === 0) {
          // console.log(data);
          if (data.data != null && data.data != undefined) {
            var l = [];
            var b = [];
            var x;
            for (let key in data.data) {
              x = key;
              var m =
                SaveCurveName[0].stationdescribe +
                " > " +
                SaveCurveName[0].devicedescribe +
                " > " +
                SaveCurveName[0].terminaldescribe +
                " > " +
                key +
                "折线图";
              for (let x in data.data[key]) {
                l.push(x);
                b.push(data.data[key][x]);
              }
            }
            getHcurve(l, b, m, x);
          }
        }
      },
      error: function () {
        layer.msg("数据请求错误,请检查时间格式！");
        layer.close(index);
      },
      // ****************************************//
    });
  }

  // 获取时间 请求数据
  // ****************************************//
  $("#CurveSeach").click(function () {
    var beginTime = $("#beginTime").val();
    var endTime = $("#endTime").val();

    // 判断时间非空
    if (beginTime != "" && endTime != "") {
      function getDaysByDateString(dateString1, dateString2) {
        var startDate = Date.parse(dateString1);
        var endDate = Date.parse(dateString2);
        var diffDate = endDate - startDate + 1 * 24 * 60 * 60 * 1000; //
        var days = parseInt(diffDate / (1 * 24 * 60 * 60 * 1000));
        return days;
      }
      // 验证查询时间   不能过大和过小
      days = getDaysByDateString(beginTime, endTime);
      if (days > 180) {
        layer.msg("错误！查询时间段不能大于180天");
        return false;
      }
      if (days < 0 || days == 0) {
        layer.msg("错误！开始时间必须小于结束时间");
        return false;
      }
      index = layer.load(1);
      getHcurveData(beginTime, endTime);
    } else {
      layer.msg("请填写开始时间 -- 结束时间！");
    }
  });
  /***********************最近24小时***********************/
  $("#24hours").click(function () {
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
    var s1 = GMTToStr(start);
    var s2 = GMTToStr(end);
    index = layer.load(1);
    getHcurveData(s1, s2);
  });
  /***********************最近三天***********************/
  $("#threeDay").click(function () {
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
    var s1 = GMTToStr(start);
    var s2 = GMTToStr(end);
    index = layer.load(1);
    getHcurveData(s1, s2);
  });
  $("#week").click(function () {
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
    var s1 = GMTToStr(start);
    var s2 = GMTToStr(end);
    index = layer.load(1);
    getHcurveData(s1, s2);
  });
  /***********************最近一个月***********************/
  $("#month").click(function () {
    let end = new Date();
    let start = new Date();
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
    var s1 = GMTToStr(start);
    var s2 = GMTToStr(end);
    index = layer.load(1);
    getHcurveData(s1, s2);
  });
  /**********************************************/

  // 曲线
  function getHcurve(ll, kk, mm, xx) {
    var echartsPies = echarts.init(
      document.getElementById("echarts-pies"),
      "walden"
    );

    option = {
      title: {
        text: mm,
        textStyle: {
          color: "#1aa094",
          left: "80px",
          fontSize: 14,
        },
      },
      tooltip: {
        trigger: "axis",
      },
      grid: {
        top: 45,
        left: "3%",
        right: "4%",
        bottom: "5%",
        containLabel: true,
      },
      toolbox: {
        right: "20px",
        feature: {
          dataView: {
            show: true,
            title: "数据视图",
            //readOnly: true, //设置只读，会隐藏刷新按钮。
            lang: ["数据视图", "关闭", "导出Excel"],
            contentToOption: function (opts) {
              var filename = JSON.parse(
                sessionStorage.getItem("SaveAlarmName")
              );
              // console.log(filename);

              $("#tableExcel_Day").table2excel({
                exclude: ".noExl", //过滤位置的 css 类名
                filename: filename[0].text + "走势图" + ".xls", //文件名称
                name: "Excel Document Name.xls",
                exclude_img: true,
                exclude_links: true,
                exclude_inputs: true,
              });
            },
            optionToContent: function (opt) {
              var axisData = opt.xAxis[0].data; //坐标数据
              var series = opt.series; //折线图数据
              var tdHeads = '<td  style="padding: 5px 10px">时间-序号</td>'; //表头第一列
              var tdBodys = ""; //表数据
              //组装表头
              // for (var i = 0; i < series.length; i++) {
              tdHeads += '<td style="padding: 5px 10px">数值</td>';
              // }
              var table =
                '<table value="' +
                series[0].name +
                '" id="tableExcel_Day" border="1" style="width:100%;text-align:center" ><tbody><tr style="background:coral;">' +
                tdHeads +
                " </tr>";
              //组装表数据
              for (var i = 0, l = axisData.length; i < l; i++) {
                for (var j = 0; j < series.length; j++) {
                  var temp = series[j].data[i];
                  if (temp != null && temp != undefined) {
                    tdBodys += "<td>" + parseFloat(temp) + "</td>";
                  } else {
                    tdBodys += "<td></td>";
                  }
                }
                table +=
                  '<tr class="myColor"><td style="padding: 5px 10px">' +
                  axisData[i] +
                  "</td>" +
                  tdBodys +
                  "</tr>";
                tdBodys = "";
              }
              table += "</tbody></table>";
              return table;
            },
          },
          saveAsImage: { backgroundColor: "#fff" },
        },
      },
      xAxis: [
        {
          type: "category",
          boundaryGap: true,
          data: ll,
          axisLabel: {
            fontSize: 13, //字体大小
            interval: "auto",
            showMaxLabel: true,
            rotate: 45,
          },
          axisLine: {
            lineStyle: {
              color: "#1aa094",
              width: 2, //这里是为了突出显示加上的
            },
          },
        },
      ],
      dataZoom: [
        // {
        //   type: "slider",
        //   realtime: true,
        //   bottom: -2,
        //   start: 0,
        //   end: 100,
        // },
        {
          type: "inside",
          realtime: true,
          start: 0,
          end: 100,
        },
      ],
      yAxis: {
        type: "value",
        axisLabel: {
          formatter: function (res) {
            // 判断给单位
            if (JSON.parse(HcurveName)[0].unitOfMeasurement != null) {
              //    增加中括号
              return [res + JSON.parse(HcurveName)[0].unitOfMeasurement];
            } else {
              return res;
            }
          },
        },
        axisLine: {
          lineStyle: {
            color: "#1aa094",
            width: 2, //这里是为了突出显示加上的
          },
        },
      },
      series: [
        {
          name: xx,
          type: "line",
          showSymbol: false, //悬停才显示圆圈
          //    stack: '总量',
          data: kk,
          itemStyle: {
            normal: {
              //    color:'rgb(255,87,34)'
              color: "red",
              //    color:'#1aa094'
            },
          },
          markPoint: {
            data: [
              { type: "max", name: "最大值" },
              { type: "min", name: "最小值" },
            ],
          },
        },
      ],
    };

    echartsPies.setOption(option);
  }

  /**********************************************/
  //2020-03-27 HF  请求曲线接口
  function getHcurveData(beginTime, endTime) {
    $.ajax({
      url:
        "/oms-web/curves-authority-points?token=" +
        token +
        "&beginTime=" +
        beginTime +
        "&endTime=" +
        endTime,
      dataType: "json",
      type: "POST",
      data: HcurveName,
      contentType: "application/json",
      success: function (data) {
        if (data.code === 0) {
          // loading加载动画
          // console.log(data);
          layer.close(index);
          if (data.data != null && data.data != undefined) {
            var l = [];
            var b = [];
            var x;

            for (let key in data.data) {
              x = key;
              var m =
                SaveCurveName[0].stationdescribe +
                " > " +
                SaveCurveName[0].devicedescribe +
                " > " +
                SaveCurveName[0].terminaldescribe +
                " > " +
                key +
                "折线图";
              for (let x in data.data[key]) {
                l.push(x);
                b.push(data.data[key][x]);
              }
            }
            getHcurve(l, b, m, x);
          }
        }
      },
      error: function () {
        layer.msg("数据请求错误,请检查时间格式！");
        layer.close(index);
      },
      // ****************************************//
    });
  }

  //获取时间函数
  function GMTToStr(time) {
    function add0(m) {
      return m < 10 ? "0" + m : m;
    } //避免少0
    var time = new Date(time);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    return (
      year +
      "-" +
      add0(month) +
      "-" +
      add0(date) +
      " " +
      add0(hours) +
      ":" +
      add0(minutes) +
      ":" +
      add0(seconds)
    );
  }

  $("#beginTime").datetimepicker({
    language: "zh-CN", //显示中文
    format: "yyyy-mm-dd hh:ii:ss", //显示格式
    // minView: "month",//设置只显示到月份
    initialDate: new Date(), //初始化当前日期
    autoclose: true, //选中自动关闭
    todayBtn: true, //显示今日按钮
    // minView:'month',
    language: "zh-CN",
  });
  $("#endTime")
    .datetimepicker({
      language: "zh-CN", //显示中文
      format: "yyyy-mm-dd hh:ii:ss", //显示格式
      // minView: "month",//设置只显示到月份
      initialDate: new Date(), //初始化当前日期
      autoclose: true, //选中自动关闭
      todayBtn: true, //显示今日按钮
      // minView:'month',
      language: "zh-CN",
    })
    .on("changeDate", function (ev) {
      window.clearInterval(cltime);
    });
});
